import { Component } from '@angular/core';
import { NavController, ToastController } from 'ionic-angular';
import { Camera, CameraOptions } from '@ionic-native/camera';
import { HttpResponse } from '@angular/common/http';
import { RestService } from '../../app/services/rest.service';
import { TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'page-helpsuggest',
  templateUrl: 'helpsuggest.html'
})
export class HelpSuggestPage {
  private win: any = window;
  suggestion = '';
  phone = '';
  user: any;
  isLoading = false;
  finished = false;

  images: Array<{ src: string }>;
  constructor(public navCtrl: NavController,
              private camera: Camera,
              private toastCtrl: ToastController,
              public translate: TranslateService,
              private rest: RestService) {
    this.user = this.rest.getUser();
    this.images = [];
  }

  navBack() {
    this.navCtrl.pop();
  }

  takephoto() {
    const options: CameraOptions = {
      quality: 50,
      sourceType: this.camera.PictureSourceType.CAMERA,
      destinationType: this.camera.DestinationType.FILE_URI,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE
    }

    this.camera.getPicture(options).then((imagePath) => {
      imagePath = this.win.Ionic.WebView.convertFileSrc(imagePath);
      this.images.unshift({
        src: imagePath
      });
    }, (err) => {
      // this.showToast(err);
      console.log('Failed to get picture.');
    });
  }

  submit() {
    if (this.images.length > 0) {
      this.rest.getLocalFile(this.images).subscribe(blobs => {
        const files = [];
        blobs.forEach((blob: any, index) => {
          const file = new File([blob], 'image' + index + '.jpg', {type: blob.type, lastModified: Date.now()});
          files.push(file);
        });

        this.uploadFiles(files);
      });
    } else {
      this.uploadFiles([]);
    }
  }

  uploadFiles(files: File[]) {
    this.isLoading = true;
    this.rest.upload(files, this.suggestion, this.phone, this.user.instName).subscribe(event => {
      if (event instanceof HttpResponse) {
        console.info('Upload files to server succeeded!');
        this.isLoading = false;
        this.finished = true;
      }
    }, message => {
      this.isLoading = false;
      this.showToast(this.translate.get('suggestionUploadFail')['value']);
    });
  }

  getMessage() {
    if (this.isLoading) {
      return this.translate.get('isLoading')['value'];
    } else if (this.finished) {
      return this.translate.get('suggestionUploaded')['value'];
    }

    return this.translate.get('submit')['value'];
  }

  showToast(message) {
    const toast = this.toastCtrl.create({
      message: message,
      duration: 5000,
      position: 'bottom'
    });

    toast.present(toast);
  }

  deletephoto() {
    this.images.shift();
  }
}
